from collections.abc import Generator
from typing import Annotated

import jwt
from fastapi import Depends, HTTPException, status, Request
from fastapi.security import HTTPBearer
from jwt.exceptions import InvalidTokenError
from pydantic import ValidationError
from sqlmodel import Session

from app.core import security
from app.core.config import settings
from app.core.db import engine
from app.models import TokenPayload, User,UserMeResult


# bearer_security = HTTPBearer()


def get_db() -> Generator[Session, None, None]:
    with Session(engine) as session:
        # The pool_pre_ping setting in the engine will handle connection validation automatically
        # No need to manually test connection here as it's handled by the engine settings
        yield session


SessionDep = Annotated[Session, Depends(get_db)]
TokenDep = Annotated[str, Depends(security)]


async def get_current_user(
    session: SessionDep,
    request: Request,
) -> UserMeResult:
    token = request.headers.get("Authorization")
    if not token:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="No authorization token provided",
        )
    
    if token.startswith("Bearer "):
        token = token[7:]
        
    try:
        payload = jwt.decode(
            token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
        )
        token_data = TokenPayload(**payload)
    except (InvalidTokenError, ValidationError):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Could not validate credentials",
        )
    # user = session.get(User, token_data.userId)
    if token_data.userId not in ('admin','editor'):
        raise HTTPException(status_code=404, detail="User not found")
    # if user.status!='ENABLED':
    #     raise HTTPException(status_code=400, detail="Inactive user")
    if token_data.userId=='admin':
        roles=['admin']
    else:
        roles=['editor']
    return UserMeResult(username=token_data.userId,roles=roles)


CurrentUser = Annotated[UserMeResult, Depends(get_current_user)]


def get_current_active_superuser(current_user: CurrentUser) -> User:
    if not current_user.is_superuser:
        raise HTTPException(
            status_code=403, detail="The user doesn't have enough privileges"
        )
    return current_user
